import './index.scss'
import {
    Breadcrumb, Button, Radio, Space, Table, Modal, Avatar, List, Tag, Row, Col, Switch, InputNumber, Form, Input
} from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom"

import OrderHeader from '../../../../components/WL/orderHeader'
import { getUser, setTag, editIntegral } from '../../../../api/WL/userQuery'

import moment from 'moment';
function BtnList(props) {
    console.log(props.data.blooen);
    return <Button key={props.data.id} type={props.data.blooen ? 'primary' : 'text'} onClick={() => { props.fn(props.data.id) }}>{props.data.name}</Button>
}

const Query = () => {
    const [data, setData] = useState([]);

    //循环每一项标签
    const btnListRender = (arr) => {
        let list = []
        arr.map((v, i) => list.push(<Tag key={i}>{v.labelName}</Tag>))
        return list
    }
    //循环每一个会员等级
    const btnListRender2 = (arr) => {
        let list = []
        arr.map((v, i) => list.push(<p key={i} style={{ color: "#1890FF" }}>{v.vipName}</p>))
        return list
    }

    //查询所有用户的初始化数据
    const userAllData = () => {
        getUser().then((res) => {
            console.log(res);
            if (res.code === 200) {
                let _data = res.data;
                if (_data.length > 0) {
                    _data.forEach(item => {
                        item.registrationTime = moment(item.registrationTime).format('YYYY-MM-DD mm:ss')
                    });
                }
                setData(_data);
            }
        })
    }
    useEffect(() => {
        userAllData();
    }, [])

    //表格的状态
    const onChange = (checked) => {
        console.log(`switch to ${checked}`);
    };
    //表格
    const columns = [
        {
            title: '用户信息',
            key: 'name',
            width: "160px",
            render: (_, record) => (
                <List itemLayout="horizontal">
                    <List.Item>
                        <List.Item.Meta
                            avatar={<Avatar src={'http://192.168.221.237:8006/' + record.picture} />}
                            title={record.userName}
                            description={record.phone}
                        />
                    </List.Item>
                </List>
            ),
        },
        {
            title: '会员等级',
            key: 'vipName',
            render: (_, record) => (btnListRender2(record.vipLevelList)),
        },
        {
            title: '用户标签',
            key: 'labelName',
            render: (_, record) => (btnListRender(record.userLabelList)),
        },
        {
            title: '消费次数',
            key: 'orderQuantity',
            dataIndex: 'orderQuantity',
        },
        {
            title: '消费金额（元）',
            key: 'orderMoney',
            dataIndex: 'orderMoney',
        },
        {
            title: '用户状态',
            key: 'userState',
            render: (_, record) => (
                <Space size="middle">
                    < Switch defaultChecked onChange={onChange} checked={record.userState === '0' ? true : false} />
                </Space>
            ),
        }, {
            title: '注册时间',
            key: 'registrationTime',
            dataIndex: 'registrationTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space wrap={true} size="small">
                    <Button size="small" type='link' onClick={() => userDesc(record.id)
                    } > 用户详情</Button >
                    <Button size="small" type='link' onClick={() => EditQian(record.userId, record.userLabelList)}>编辑标签</Button>
                    <Button size="small" type='link' onClick={() => EditFen(record)}>修改积分</Button>
                    <Button size="small" type='link' onClick={() => EditZhang(record.id)}>修改成长值</Button>
                    <Button size="small" type='link' onClick={() => showDeleteConfirm(record.id)}>删除</Button>
                </Space >
            ),
        },
    ];

    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        }
    };
    const [selectionType, setSelectionType] = useState('checkbox');

    //编辑标签的模态框
    const tagData = [{
        id: 1,
        name: '标签一',
        blooen: false
    }, {
        id: 2,
        name: '标签二',
        blooen: false
    }, {
        id: 3,
        name: '标签三',
        blooen: false
    }, {
        id: 4,
        name: '标签四',
        blooen: false
    }, {
        id: 5,
        name: '标签五',
        blooen: false
    }]
    const [dataTag, setDataTag] = useState([])
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [tagFrom, setTagFrom] = useState({});

    const handleOk = () => {
        setIsModalVisible(false);
        let obj = dataTag
        let arr = []
        obj.forEach(v => {
            if (v.blooen) {
                arr.push(v.id)
            }
        })
        let obj2 = tagFrom
        obj2.userLabelList = arr
        setTag(obj2).then(res => {
            console.log(res);
            if (res.code === 200) {
                userAllData();
            }
        })

    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const EditQian = (userId, tagarr) => {
        let obj = tagData
        obj.forEach(v => {
            for (let i = 0; i < tagarr.length; i++) {
                if (v.id == tagarr[i].labelId) {
                    v.blooen = true
                }
            }
        })
        console.log(obj, 323);
        setDataTag([...obj])
        setIsModalVisible(true);
        setTagFrom({ userId })

    };

    const clickPick = (val) => {
        console.log(val);
        let obj = dataTag
        obj.forEach(v => {
            if (v.id == val) {
                v.blooen = !v.blooen
            }
        })
        // console.log(obj);
        setDataTag([...obj])
    }
    //修改积分的模态框
    const [isModalVisible2, setIsModalVisible2] = useState(false);
    const [la] = Form.useForm()

    const handleOk2 = () => {
        setIsModalVisible2(false);
    };

    const handleCancel2 = () => {
        setIsModalVisible2(false);
    };
    const EditFen = (v) => {
        setIsModalVisible2(true);
        console.log(v);
        la.setFieldsValue(v)
    }

    //修改积分中的表单
    const onFinish = (values) => {
        console.log('Success:', values);
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const onChangeNum = (value) => {
        console.log('changed', value);
    };

    //修改成长值
    const [isModalVisible3, setIsModalVisible3] = useState(false);

    const handleOk3 = () => {
        setIsModalVisible3(false);
    };

    const handleCancel3 = () => {
        setIsModalVisible3(false);
    };
    const EditZhang = () => {
        setIsModalVisible3(true);
    }

    //修改成长值中的表单
    const onFinish2 = (values) => {
        console.log('Success:', values);
    };

    const onFinishFailed2 = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const onChangeNum2 = (value) => {
        console.log('changed', value);
    };

    //删除的模态框
    const { confirm } = Modal;
    const showDeleteConfirm = () => {
        confirm({
            title: '删除用户',
            icon: <ExclamationCircleOutlined />,
            content: '删除后用户信息无法恢复，确定删除此用户吗？',
            okText: '确认',
            cancelText: '取消',
            centered: true,

            onOk() {
                console.log('OK');
            },

            onCancel() {
                console.log('Cancel');
            },
        });
    };

    //用户详情的页面跳转
    const navigate = useNavigate();
    const userDesc = () => {
        navigate('/home/user/descUser');
    }

    //新增会员的模态框
    const [isModalVisible4, setIsModalVisible4] = useState(false);

    const addUser = () => {
        setIsModalVisible4(true);
    }

    const handleOk4 = () => {
        setIsModalVisible4(false);
    };

    const handleCancel4 = () => {
        setIsModalVisible4(false);
    };

    //新增会员的表单
    const onFinish4 = (values) => {
        console.log('Success:', values);
    };

    const onFinishFailed4 = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };


    //表格的页码
    const showTotal = (total) => `数量 ${total} 条`;

    return <div className='mainGoods'>
        <div className='headerGoods'>
            <div className='headerGoodsTop'>
                <div>
                    <Breadcrumb>
                        <Breadcrumb.Item>用户管理</Breadcrumb.Item>
                        <Breadcrumb.Item>用户查询</Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <h2>用户查询</h2>
            </div>
            <hr />
            <div className='headerGoodsBottom'>
                <OrderHeader />
            </div>
        </div>

        <div className='sectionGoods'>
            <div className='sectionItem1'>
                <p>用户列表</p>
                <div>
                    <Button type="primary" icon={<PlusOutlined />}>
                        导入用户
                    </Button>
                    &nbsp;&nbsp;&nbsp;
                    <Button type="primary" icon={<PlusOutlined />} onClick={addUser}>
                        新建
                    </Button>
                </div>
            </div>
            <div className='sectionItem2'>
                <Table
                    rowKey={(record) => record.userId}
                    rowSelection={{
                        type: selectionType,
                        ...rowSelection,
                    }}
                    columns={columns}
                    dataSource={data}
                    pagination={{
                        total: data.length,
                        showTotal: showTotal,
                        showSizeChanger: true,
                        showQuickJumper: true,
                    }}
                />

            </div>
        </div>

        {/* 修改标签的模态框 */}
        <Modal title="编辑标签" centered={true} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
            {dataTag.map((v, i) => <BtnList data={v} key={i} fn={clickPick} />)}
        </Modal>
        {/* 修改积分的模态框 */}
        <Modal title="修改积分" centered={true} visible={isModalVisible2} onOk={handleOk2} onCancel={handleCancel2}>
            <Form
                form={la}
                name="basic"
                layout='vertical'
                labelCol={{
                    span: 8,
                    offset: 2
                }}
                wrapperCol={{
                    span: 20,
                    offset: 2
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item
                    label="当前积分"
                    name="integral"
                >
                    <Input disabled />
                </Form.Item>

                <Form.Item
                    label="数量"
                    name="integralNum"
                >
                    <InputNumber style={{ width: '392px' }} size='large' min={1} max={100} onChange={onChangeNum} />
                </Form.Item>

                <Form.Item
                    label="操作备注"
                    name="integralNote"
                >
                    <Input placeholder='请输入...' />
                </Form.Item>
            </Form>
        </Modal>
        {/* 修改成长值 */}
        {/* 修改积分的模态框 */}
        <Modal title="修改成长值" centered={true} visible={isModalVisible3} onOk={handleOk3} onCancel={handleCancel3}>
            <Form
                name="basic"
                layout='vertical'
                labelCol={{
                    span: 8,
                    offset: 2
                }}
                wrapperCol={{
                    span: 20,
                    offset: 2
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish2}
                onFinishFailed={onFinishFailed2}
                autoComplete="off"
            >
                <Form.Item
                    label="当前成长值"
                    name="username"
                >
                    <Input disabled />
                </Form.Item>

                <Form.Item
                    label="数量"
                    name="num"
                >
                    <InputNumber style={{ width: '392px' }} size='large' min={1} max={100} onChange={onChangeNum2} />
                </Form.Item>

                <Form.Item
                    label="操作备注"
                    name="bei"
                >
                    <Input placeholder='请输入...' />
                </Form.Item>
            </Form>
        </Modal>
        {/* 新增会员的模态框 */}
        <Modal title="新增会员" visible={isModalVisible4} onOk={handleOk4} onCancel={handleCancel4}>
            <Form
                name="basic"
                layout='vertical'
                labelCol={{
                    span: 10,
                    offset: 3
                }}
                wrapperCol={{
                    span: 24,
                    offset: 3
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Row>
                    <Col>
                        <Form.Item
                            label="用户姓名"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <Col>
                        <Form.Item
                            label="联系方式"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={10}>
                        <Form.Item
                            label="用户性别"
                            name="userSex"
                        >
                            <Radio.Group defaultValue='a'>
                                <Radio value="a">男</Radio>
                                <Radio value="b">女</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Col>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <Col>
                        <Form.Item
                            label="用户年龄"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Item
                            label="微信号"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <Col>
                        <Form.Item
                            label="用户职业"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Item
                            label="常用收货人"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <Col>
                        <Form.Item
                            label="详细地址"
                            name="username"
                        >
                            <Input style={{ width: '200px' }} />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={9}>
                        <Form.Item
                            label="用户备注"
                            name="username"
                        >
                            <Input style={{ width: '300px' }} />
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
        </Modal>
    </div >
}
export default Query;